package org.mtmi.ui.controls.popups;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.Point;
import org.mtmi.ui.GraphicUtil;
import org.mtmi.ui.M;
import org.mtmi.ui.controls.Button;
import org.mtmi.ui.controls.listeners.TapAdapter;
import org.mtmi.ui.controls.listeners.TapEvent;
import org.mtmi.ui.scenes.COLOR;
import org.mtmi.ui.scenes.ColorManager;
import org.mtmi.ui.scenes.FontManager;
import org.mtmi.ui.scenes.Scene;

/**
 * Popup with one button. Default button (short constructor) is "Ok".
 * This popup is typically used to display information.
 * All elements existing in the display is darkened and can no longer be touched.
 * The popup gain the entire focus until the button is touched. 
 * @author jgout
 *
 */
public class OneButtonPopup extends Popup {

	private static final int hMargin = 50;
	private static final int vMargin = 50;
	private static final int vSpan = 150;
	private String text;
	private Button button;
	private Point textSize;
	
	public OneButtonPopup( Scene scene, String text, int flags ) {
		this( scene, text, "Ok", flags );
	}

	public OneButtonPopup(Scene scene, String text, String button, int flags ) {
		super( scene, flags );
		this.text = text; 
		computeQuestionSize();
		createButton(button);
	}

	private void computeQuestionSize() {
		int limit = getScene().getSize().x/2;
		textSize = getSize(text);
		if(textSize.x > limit) {
			//- question is too large, need to cut it.
			text = cutText(text);
			textSize = getSize(text);
		}
	}

	private void createButton(String b) {
		button = new Button( getScene(), flags & M.SCENE_EDITOR_CONTROL );
		button.setText(b);
		int x = getSize().x/2 - button.getSize().x/2;
		int y = getSize().y/3 + textSize.y+vSpan;
		button.setLocation(x, y);
		button.addTapListener(new TapAdapter() {
			@Override
			public void controlTappedDown(TapEvent event) {
				terminate();
			}
		});
	}

	private void terminate() {
		dispose();
		button.dispose();
	}

	@Override
	public void paintContent(GC gc, int w, int h) {
		gc.setForeground( COLOR.sceneFg );
		gc.setBackground( COLOR.sceneBg );
		gc.setLineWidth(4);
		int height = textSize.y+vSpan+button.getSize().y+(2*vMargin);
		Path path = GraphicUtil.getRoundRectangle(gc, (w-textSize.x)/2 - hMargin, h/3-vMargin, textSize.x+2*hMargin, height, hMargin, vMargin);
		gc.fillPath(path);
		gc.setFont(FontManager.getInstance().getNormalFont());
		gc.drawText(text, (w-textSize.x)/2, h/3);
		gc.drawPath(path);
	}

	@Override
	public String toString() {
		//- 20 first characters of the text
		return text.substring(0, 20);
	}
	
}
